package com.egoo.ticket.server.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.egoo.eeip.eeif.framework.base.util.common.ObjectUtil;
import com.egoo.ticket.server.dao.WorkOrderExcelDao;
import com.egoo.ticket.server.pojo.dto.WorkOrderExcelOutDto;
import com.egoo.ticket.server.pojo.vo.WorkOrderExportVo;
import com.egoo.ticket.server.project.ProjectConstant;
import com.egoo.ticket.server.project.jincheng.JinChengBaseUtil;
import com.egoo.ticket.server.service.WorkOrderExcelService;
import com.egoo.ticket.server.utils.common.CommonUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author Administrator
 */
@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class WorkOrderExcelServiceImpl  implements WorkOrderExcelService {

	@Autowired
	private WorkOrderExcelDao workOrderExcelDao;

	@Value("${server.project-sign}")
	private String projectSign;

	@Autowired
	private JinChengBaseUtil jinChengBaseUtil;

	public SimpleDateFormat sdfTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	/**
	 * TODO 根据工单id集合关联work_order工单表与work_order_status工单状态表获取导出信息
	 *
	 * @param workOrderIdList
	 * @return
	 */
	@Override
	public List selectByIdList(List<String> workOrderIdList) {

		List<WorkOrderExportVo> workOrderExportList = workOrderExcelDao.selectByIdList(workOrderIdList);

		// 组装Excel上传内容数据
		return handleExcelData(workOrderExportList);

	}

	/**
	 * @Description:
	 * @Author: xwy
	 * @Date: 2020/11/4 18:36
	 * @param workOrderIdList:
	 * @return: java.util.Map<java.lang.String,java.lang.Object>
	 **/
	@Override
	public Map<String, Object> selectByIdListDynamic(List<String> workOrderIdList,String projectSign) {
		Map<String,Object> map = new HashMap<>();
		//从json配置文件获取数据
		JSONArray jsonArray=getHeadJsonByProjectSign(projectSign);
		List<Map> headMap =  JSON.parseArray(jsonArray.toJSONString(), Map.class);
		//返回表头信息集合 筛选出 isOutExcel键存在并且值为true的元素重新组装  每个元素保留三个属性 belongToTable  prop  label
		List<Map<String,String>> headList=getHeadList(headMap);

		//根据动态表头字段拼接查询的sql
		StringBuffer sb=new StringBuffer();
		sb.append(" SELECT ");
		headList.forEach(h->{
			String bToTable=String.valueOf(h.get("belongToTable"));
			String prop=String.valueOf(h.get("prop"));
			//表字段
			if(bToTable.equals("work_order")){

				//状态获取中文
				if(prop.equals("status_id")){
					sb.append(" b.name as status_id, ");
				}
				//时间特殊处理
				else if(prop.endsWith("_time")){
					sb.append("date_format(a."+prop+",'%Y-%m-%d %H:%i:%s') as "+prop+",");
				}
				else if(prop.equals("work_order_type_id")){
					sb.append(" c.name as work_order_type_id, ");
				}
				else {
					sb.append(" a."+ prop+", ");
				}
			}
			/* SELECT json_extract(custom_field,'$.id_number') from 	work_order */
			//自定json
			if(bToTable.equals("work_order.custom_field")){
				sb.append("JSON_UNQUOTE(json_extract (a.custom_field"+ ",'$."+prop+"')) as "+prop+"," );
			}
		});
		//删除最后一个逗号
		sb.deleteCharAt(sb.lastIndexOf(","));
		String ss = String.join(",", workOrderIdList);
		sb.append(" FROM work_order a LEFT JOIN work_order_status b " +
				"ON b.id = a.status_id LEFT JOIN work_order_type c  ON a.work_order_type_id=c.id WHERE a.id in ("+ss+") order by a.create_time desc");

		List<LinkedHashMap<String,Object>>  reList=   workOrderExcelDao.selectByIdListDynamic(sb.toString());
		List<List<Object>> dataList=Lists.newArrayList();
		//表头字段集合
		List<String> heads=Lists.newArrayList();
		headList.forEach(head->{
			heads.add(String.valueOf(head.get("label")));
		});

		for (Map<String, Object> m : reList)
		{
			List<Object> tempList=Lists.newArrayList();
			for (Object v : m.values())
			{
				if(v==null){
					 tempList.add("");
				}else{
					//如果值不是字符串转字符串
					if(!(v instanceof String)){
						tempList.add(String.valueOf(v));
					}else {
						tempList.add(v);
					}
				}
			}
			dataList.add(tempList);
		}

		map.put("heads",heads);
		map.put("dataList",dataList);
		return map;
	}

	/**
	 * TODO 组装Excel上传内容数据
	 *
	 * @param workOrderExportList
	 * @return
	 */
	private List handleExcelData(List<WorkOrderExportVo> workOrderExportList) {
		//组装产品版本的数据
		List dataList =null;
		if (ProjectConstant.ProjectSign.PRODUCT.equals(projectSign) || null ==projectSign) {
			dataList = productData(workOrderExportList);
		}
		else if (ProjectConstant.ProjectSign.JINCHNEG.equals(projectSign)){
			dataList = jinChengBaseUtil.jinChengData(workOrderExportList);
		}
		return dataList;
	}

	/**
	 * @Description:
	 * @Author: xwy
	 * @Date: 2020/11/4 18:51
	 * @param mapList:
	 * @return: java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
	 **/
	private List<Map<String,String>>  getHeadList(List<Map> mapList){
		List<Map<String,String>>  list= Lists.newArrayList();
		mapList.forEach(n->{
			//如果isOutExcel不为空
			if(ObjectUtil.isNotEmpty(n.get("isOutExcel"))){
				//并且isOutExcel 为true
				if(Boolean.parseBoolean(String.valueOf(n.get("isOutExcel"))) ){
					Map<String,String> tempMap= Maps.newHashMap();
					tempMap.put("belongToTable",String.valueOf(n.get("belongToTable")));
					tempMap.put("prop",String.valueOf(n.get("prop")));
					tempMap.put("label",String.valueOf(n.get("label")));
					list.add(tempMap);
				}
			}
		});
		return list;
	}

	/**
	 * @Description:
	 * @Author: xwy
	 * @Date: 2020/11/4 18:18
	 * @param sign: 
	 * @return: com.alibaba.fastjson.JSONArray
	 **/
	private  JSONArray getHeadJsonByProjectSign(String sign){
		return CommonUtil.readConfig("/headfieldconfig/sysFilterHeadField-"+sign+".json");
	}


	/**
	 * @Author: Donny_dong
	 * @Description: 组装产品版本导出数据
	 * @Param:
	 * @return:
	 * @Date: 2020/8/18
	 */
	private List<WorkOrderExcelOutDto> productData(List<WorkOrderExportVo> workOrderExportList) {
		List<WorkOrderExcelOutDto> dataList = new ArrayList<WorkOrderExcelOutDto>();
		for (WorkOrderExportVo workOrderExport : workOrderExportList) {
			WorkOrderExcelOutDto workOrderExcelOutDto = new WorkOrderExcelOutDto();
			// 复制导出显示基础字段
			BeanUtils.copyProperties(workOrderExport, workOrderExcelOutDto);
			// 设置工单处理时长
			if (StringUtils.isNotBlank(workOrderExport.getCloseTime())&& StringUtils.isNotBlank(workOrderExport.getCreateTime()) ){
				long timeCreate = 0;
				long timeClose = 0;
				try {
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					timeCreate = sdf.parse(workOrderExport.getCreateTime()).getTime();
					timeClose = sdf.parse(workOrderExport.getCloseTime()).getTime();
				} catch (ParseException e) {
					log.error("工单导出创建时间和关闭时间格式化异常！");
				}
				Double handleTime = (timeClose - timeCreate)/1000/3600.0;
				BigDecimal bigDecimal = BigDecimal.valueOf(handleTime);
				handleTime = bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
				workOrderExcelOutDto.setHandlerTime(handleTime);
			}
			dataList.add(workOrderExcelOutDto);
		}
		return dataList;
	}
}
